﻿using System.IO.Ports;
using System.Text;
using Om.Core.Extension;
using TouchSocket.Core;
using TouchSocket.SerialPorts;
using TouchSocket.Sockets;

namespace Om.Core.Singleton;

public class CmdAirClient : SingletonBase<CmdAirClient>
{

    /// <summary>
    /// 空中站客户端
    /// </summary>
    public SerialPortClient Client { get; set; } = new SerialPortClient();

    public CmdAirClient()
    {
        Client.Received += AirClient_Received;
    }
    private async Task AirClient_Received(ISerialPortClient client, ReceivedDataEventArgs e)
    {
        string mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
        var dataArr = mes.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        var cmd = dataArr[0];

        switch (cmd)
        {
            case GroundCmdTokens.CmdTemperature:
            {
                var data = dataArr[1];
                var p = data.Split(',');
                var x = double.Parse(p[0]);
                var y = double.Parse(p[1]);
                var temp = await DevicesManager.Instance.IrCamera.GetPointTemperature(x, y);
                await client.SendAsync(cmd + Environment.NewLine + temp);
            }
                break;
            case GroundCmdTokens.CmdStartCapture:
            {
                var data = dataArr[1];
                if (data.StartsWith("n") && double.TryParse(data.Replace("n", "").Trim(), out double seconds))
                {
                    StartCaptureTask(seconds);
                }
                else
                {
                    await Capture();
                }

                await client.SendAsync(cmd + Environment.NewLine + "ok");
            }
                break;
            case GroundCmdTokens.CmdStopCapture:
                await StopCapture();
                await client.SendAsync(cmd + Environment.NewLine + "ok");
                break;
        }
    }

    public async Task Connect(string portName)
    {
        var client = Client;
        await client.SafeCloseAsync();
        await client.SetupAsync(new TouchSocketConfig()
            .SetSerialPortOption(new SerialPortOption()
            {
                PortName = portName,
                BaudRate = 9600,
                DataBits = 8,
                Parity = Parity.None,
                StopBits = StopBits.One,
            }).SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter()
                { CacheTimeout = TimeSpan.FromMilliseconds(100) })
        );
        await client.TryConnectAsync();
    }

    public async Task Capture()
    {
        // 热成像仪
        DevicesManager.Instance.IrCamera.Capture(Path.Combine("Pictures",
            DateTime.Now.ToString("ir_yyyyMMddHHmmssfff") + ".jpg"));
        // 可见光近红外高光谱，写文件
        var ggpFilePath = DevicesConfig.Instance.GgpFilePath;
        File.CreateText(ggpFilePath);

        // todo 其他，同步器
    }
    private bool _isCapturing = false;
    public async Task StartCaptureTask(double seconds)
    {
        //_isCapturing = true;
        //while (_isCapturing)
        //{
        //    await Capture();
        //    await Task.Delay(TimeSpan.FromSeconds(seconds));
        //}

        if (DevicesManager.Instance.Signal?.Client?.Online != true)
            return;
        var ms = (int)(seconds * 1000);
        var res =  await DevicesManager.Instance.Signal.StartSendSignal(ms);
        LogHelper.Log($"定时信号开始： 是否成功：{res}  时间间隔：{ms}ms");
    }

    public async Task StopCapture()
    {
        //_isCapturing = false;

        if (DevicesManager.Instance.Signal?.Client?.Online != true)
            return;
        var res = await DevicesManager.Instance.Signal.StopSendSignal();
        LogHelper.Log($"定时信号停止： 是否成功：{res}");
    }
}